const NORMAL = {
  ON: true,
  OFF: false,
  KEY_B: 'KeyB',
  KEY_T: 'KeyT'
}
// 需要缓存的数据
const cache = {
  timer: null,
  code: null
}
window.onload = function () {
  listener(NORMAL.ON)
}
window.onunload = function () {
  listener(NORMAL.OFF)
}

function listener(bool) {
  const taskInputer = document.querySelector('#task-id')
  const bugInputer = document.querySelector('#bug-id')
  const jumpLink = document.querySelector('#jump-link')
  const method = bool ? 'addEventListener' : 'removeEventListener'
  taskInputer[method]('input', handleTaskInput)
  bugInputer[method]('input', handleBugInput)
  jumpLink[method]('click', handleJumpClick)
  document[method]('keypress', globalKeypress)
}
function handleTaskInput(e) {
  const value = e.target.value
  if (cache.timer) clearTimeout(cache.timer)
  cache.timer = setTimeout(() => {
    const url = `http://work.ruiyunnet.com/biz/task-view-${value.trim()}.html`
    openUrl(url)
    cache.timer = null
  }, 500)
}
function handleBugInput(e) {
  const value = e.target.value
  if (cache.timer) clearTimeout(cache.timer)
  cache.timer = setTimeout(() => {
    const url = `http://work.ruiyunnet.com/biz/bug-view-${value.trim()}.html`
    openUrl(url)
    cache.timer = null
  }, 500)
}
// 跳转按钮点击事件
function handleJumpClick(e, cusType) {
  let type = cusType
  if (e) {
    type = e.target.dataset.type
  }
  if (!type) return
  const url = `http://work.ruiyunnet.com/biz/my-${type}.html`
  openUrl(url);
}
/**
 * 新标签打开指定链接
 * @param {String} url 打开的链接
 */
function openUrl(url) {
  let properties = {url, selected: true}
  chrome.extension.sendRequest({type: 'createNewTab', properties})
}
// 全局键盘事件
function globalKeypress(e) {
  console.log('事件=====', e)
  const code = e.code
  if (code === cache.code) {
    if (code === NORMAL.KEY_B) { // 双击B键
      handleJumpClick(null, 'bug')
    } else if (code === NORMAL.KEY_T) { // 双击T键
      handleJumpClick(null, 'task')
    }
    cache.code = null
  } else {
    cache.code = code
  }
}